import router from '@/router'
import { useUserStoreHook } from '@/store/modules/user'
import { ElMessage } from 'element-plus'
import { setRouteChange } from '@/hooks/useRouteListener'
import { usePermissionStoreHook } from '@/store/modules/permission'
import { useTitle } from '@/hooks/useTitle'
import { getToken } from '@/utils/cache/cookies'
import isWhiteList from '@/config/white-list'
import routeSettings from '@/config/route'
import { fixBlankPage } from '@/utils/fix-blank-page'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
const { setTitle } = useTitle()
NProgress.configure({ showSpinner: false })
router.beforeEach(async (to, _from, next) => {
  fixBlankPage()
  NProgress.start()
  const userStore = useUserStoreHook()
  const permissionStore = usePermissionStoreHook()
  const token = getToken()

  // 判断用户是否已经登录
  if (token) {
    // 已登录用户尝试访问登录页
    if (to.path === '/login') {
      NProgress.done()
      return next({ path: '/' }) // 重定向到主页
    }
    if (!routeSettings.async) {
      // 非动态路由，使用默认角色设置权限和路由
      userStore.setRoles(routeSettings.defaultRoleId)
      permissionStore.setRoutes(routeSettings.defaultRoleId)
    } else if (!permissionStore.isDynamicRoutesAdded) {
      // 添加动态路由
      try {
        permissionStore.setRoutes(userStore.getRoles())
        permissionStore.dynamicRoutes.forEach((route) => router.addRoute(route))
        permissionStore.isDynamicRoutesAdded = true
        return next({ ...to, replace: true })
      } catch (err) {
        console.error(err)
        NProgress.done()
        userStore.resetToken()
        ElMessage.error('权限配置错误，已重定向到登录页面')
        return next('/login')
      }
    }
  } else {
    // 未登录用户
    if (isWhiteList(to)) {
      return next() // 在白名单中，直接进入
    } else {
      NProgress.done()
      return next('/login') // 重定向到登录页面
    }
  }

  next()
})

router.afterEach((to) => {
  setRouteChange(to)
  setTitle(to.meta.title as string)
  NProgress.done()
})
